package com.lanvideo.controller;

import com.lanvideo.entity.Exam;
import com.lanvideo.entity.ExamQuestion;
import com.lanvideo.entity.ExamStudent;
import com.lanvideo.entity.Question;
import com.lanvideo.entity.ExamRecord;
import com.lanvideo.entity.ExamAnswer;
import com.lanvideo.entity.User;
import com.lanvideo.service.ExamService;
import com.lanvideo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

/**
 * 考试控制器
 */
@RestController
@RequestMapping("/api/exam")
public class ExamController {
    
    @Autowired
    private ExamService examService;
    
    @Autowired
    private UserService userService;

    /**
     * 创建考试
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createExam(@RequestBody Exam exam, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(teacherId);
            if (user == null || (user.getRole() != 1 && user.getRole() != 0)) {
                result.put("success", false);
                result.put("message", "只有老师和管理员可以创建考试");
                return ResponseEntity.ok(result);
            }
            
            exam.setTeacherId(teacherId);
            exam.setStatus(0); // 草稿状态
            
            if (examService.createExam(exam)) {
                result.put("success", true);
                result.put("message", "考试创建成功");
            } else {
                result.put("success", false);
                result.put("message", "考试创建失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 更新考试
     */
    @PostMapping("/update")
    public ResponseEntity<Map<String, Object>> updateExam(@RequestBody Exam exam, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null || userService.getUserById(teacherId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以修改考试");
                return ResponseEntity.ok(result);
            }
            
            if (examService.updateExam(exam)) {
                result.put("success", true);
                result.put("message", "考试更新成功");
            } else {
                result.put("success", false);
                result.put("message", "考试更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 删除考试
     */
    @PostMapping("/delete/{examId}")
    public ResponseEntity<Map<String, Object>> deleteExam(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null || userService.getUserById(teacherId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以删除考试");
                return ResponseEntity.ok(result);
            }
            
            if (examService.deleteExam(examId)) {
                result.put("success", true);
                result.put("message", "考试删除成功");
            } else {
                result.put("success", false);
                result.put("message", "考试删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取考试详情（公开接口，用于学生查看）
     */
    @GetMapping("/{examId}")
    public ResponseEntity<Map<String, Object>> getExam(@PathVariable Integer examId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Exam exam = examService.getExamById(examId);
            if (exam != null) {
                result.put("success", true);
                result.put("exam", exam);
            } else {
                result.put("success", false);
                result.put("message", "考试不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 老师获取考试详情（带权限验证）
     */
    @GetMapping("/teacher/detail/{examId}")
    public ResponseEntity<Map<String, Object>> getTeacherExamDetail(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(teacherId);
            if (user == null || user.getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看考试详情");
                return ResponseEntity.ok(result);
            }
            
            Exam exam = examService.getExamById(examId);
            if (exam == null) {
                result.put("success", false);
                result.put("message", "考试不存在");
                return ResponseEntity.ok(result);
            }
            
            // 验证老师是否有权限查看这个考试
            if (!exam.getTeacherId().equals(teacherId)) {
                result.put("success", false);
                result.put("message", "没有权限查看此考试");
                return ResponseEntity.ok(result);
            }
            
            result.put("success", true);
            result.put("exam", exam);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取老师的考试列表
     */
    @GetMapping("/teacher/list")
    public ResponseEntity<Map<String, Object>> getTeacherExams(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(teacherId);
            if (user == null || user.getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看考试列表");
                return ResponseEntity.ok(result);
            }
            
            List<Exam> exams = examService.getExamsByTeacherId(teacherId);
            result.put("success", true);
            result.put("exams", exams);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取学生的考试列表
     */
    @GetMapping("/student/list")
    public ResponseEntity<Map<String, Object>> getStudentExams(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer studentId = (Integer) session.getAttribute("userId");
            if (studentId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                return ResponseEntity.ok(result);
            }
            
            if (userService.getUserById(studentId).getRole() != 2) {
                result.put("success", false);
                result.put("message", "只有学生可以查看考试列表");
                return ResponseEntity.ok(result);
            }
            
            List<Exam> exams = examService.getAvailableExamsForStudent(studentId);
            
            // 调试日志
            System.out.println("=== ExamController.getStudentExams Debug ===");
            System.out.println("Student ID: " + studentId);
            System.out.println("Exams count: " + exams.size());
            for (Exam exam : exams) {
                System.out.println("Exam ID: " + exam.getId() + 
                    ", Title: " + exam.getTitle() + 
                    ", StudentStatus: " + exam.getStudentStatus() + 
                    ", StudentScore: " + exam.getStudentScore());
            }
            System.out.println("=== End Debug ===");
            
            result.put("success", true);
            result.put("exams", exams);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }


    /**
     * 发布考试
     */
    @PostMapping("/publish/{examId}")
    public ResponseEntity<Map<String, Object>> publishExam(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null || userService.getUserById(teacherId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以发布考试");
                return ResponseEntity.ok(result);
            }
            
            if (examService.publishExam(examId)) {
                result.put("success", true);
                result.put("message", "考试发布成功");
            } else {
                result.put("success", false);
                result.put("message", "考试发布失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 结束考试
     */
    @PostMapping("/end/{examId}")
    public ResponseEntity<Map<String, Object>> endExam(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null || userService.getUserById(teacherId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以结束考试");
                return ResponseEntity.ok(result);
            }
            
            if (examService.endExam(examId)) {
                result.put("success", true);
                result.put("message", "考试结束成功");
            } else {
                result.put("success", false);
                result.put("message", "考试结束失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 添加题目到考试
     */
    @PostMapping("/{examId}/add-question/{questionId}")
    public ResponseEntity<Map<String, Object>> addQuestionToExam(@PathVariable Integer examId, @PathVariable Integer questionId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(userId);
            if (user == null || (user.getRole() != 1 && user.getRole() != 0)) {
                result.put("success", false);
                result.put("message", "只有老师和管理员可以添加题目");
                return ResponseEntity.ok(result);
            }
            
            if (examService.addQuestionToExam(examId, questionId)) {
                result.put("success", true);
                result.put("message", "题目添加成功");
            } else {
                result.put("success", false);
                result.put("message", "题目添加失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 从考试中移除题目
     */
    @PostMapping("/{examId}/remove-question/{questionId}")
    public ResponseEntity<Map<String, Object>> removeQuestionFromExam(@PathVariable Integer examId, @PathVariable Integer questionId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(userId);
            if (user == null || (user.getRole() != 1 && user.getRole() != 0)) {
                result.put("success", false);
                result.put("message", "只有老师和管理员可以移除题目");
                return ResponseEntity.ok(result);
            }
            
            if (examService.removeQuestionFromExam(examId, questionId)) {
                result.put("success", true);
                result.put("message", "题目移除成功");
            } else {
                result.put("success", false);
                result.put("message", "题目移除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取考试题目列表（公开接口）
     */
    @GetMapping("/{examId}/questions")
    public ResponseEntity<Map<String, Object>> getExamQuestions(@PathVariable Integer examId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<ExamQuestion> questions = examService.getExamQuestions(examId);
            result.put("success", true);
            result.put("questions", questions);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 老师获取考试题目列表（带权限验证）
     */
    @GetMapping("/teacher/{examId}/questions")
    public ResponseEntity<Map<String, Object>> getTeacherExamQuestions(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(teacherId);
            if (user == null || user.getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看考试题目");
                return ResponseEntity.ok(result);
            }
            
            // 验证老师是否有权限查看这个考试
            Exam exam = examService.getExamById(examId);
            if (exam == null || !exam.getTeacherId().equals(teacherId)) {
                result.put("success", false);
                result.put("message", "没有权限查看此考试");
                return ResponseEntity.ok(result);
            }
            
            List<ExamQuestion> questions = examService.getExamQuestions(examId);
            result.put("success", true);
            result.put("questions", questions);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取可添加的题目列表
     */
    @GetMapping("/{examId}/available-questions")
    public ResponseEntity<Map<String, Object>> getAvailableQuestions(@PathVariable Integer examId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Question> questions = examService.getAvailableQuestions(examId);
            result.put("success", true);
            result.put("questions", questions);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 添加学生到考试
     */
    @PostMapping("/{examId}/add-student/{studentId}")
    public ResponseEntity<Map<String, Object>> addStudentToExam(@PathVariable Integer examId, @PathVariable Integer studentId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(userId);
            if (user == null || (user.getRole() != 1 && user.getRole() != 0)) {
                result.put("success", false);
                result.put("message", "只有老师和管理员可以添加学生");
                return ResponseEntity.ok(result);
            }
            
            if (examService.addStudentToExam(examId, studentId)) {
                result.put("success", true);
                result.put("message", "学生添加成功");
            } else {
                result.put("success", false);
                result.put("message", "学生已存在或添加失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 从考试中移除学生
     */
    @PostMapping("/{examId}/remove-student/{studentId}")
    public ResponseEntity<Map<String, Object>> removeStudentFromExam(@PathVariable Integer examId, @PathVariable Integer studentId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(userId);
            if (user == null || (user.getRole() != 1 && user.getRole() != 0)) {
                result.put("success", false);
                result.put("message", "只有老师和管理员可以移除学生");
                return ResponseEntity.ok(result);
            }
            
            if (examService.removeStudentFromExam(examId, studentId)) {
                result.put("success", true);
                result.put("message", "学生移除成功");
            } else {
                result.put("success", false);
                result.put("message", "学生移除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取考试学生列表（公开接口）
     */
    @GetMapping("/{examId}/students")
    public ResponseEntity<Map<String, Object>> getExamStudents(@PathVariable Integer examId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<ExamStudent> students = examService.getExamStudents(examId);
            result.put("success", true);
            result.put("students", students);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 老师获取考试学生列表（带权限验证）
     */
    @GetMapping("/teacher/{examId}/students")
    public ResponseEntity<Map<String, Object>> getTeacherExamStudents(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(teacherId);
            if (user == null || user.getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看考试学生");
                return ResponseEntity.ok(result);
            }
            
            // 验证老师是否有权限查看这个考试
            Exam exam = examService.getExamById(examId);
            if (exam == null || !exam.getTeacherId().equals(teacherId)) {
                result.put("success", false);
                result.put("message", "没有权限查看此考试");
                return ResponseEntity.ok(result);
            }
            
            List<ExamStudent> students = examService.getExamStudents(examId);
            result.put("success", true);
            result.put("students", students);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }


    /**
     * 完成考试
     */
    @PostMapping("/{examId}/complete")
    public ResponseEntity<Map<String, Object>> completeExam(@PathVariable Integer examId, @RequestBody Map<String, Object> data, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer studentId = (Integer) session.getAttribute("userId");
            if (studentId == null || userService.getUserById(studentId).getRole() != 2) {
                result.put("success", false);
                result.put("message", "只有学生可以完成考试");
                return ResponseEntity.ok(result);
            }
            
            Integer score = (Integer) data.get("score");
            if (examService.completeExam(examId, studentId, score)) {
                result.put("success", true);
                result.put("message", "考试完成");
                result.put("score", score);
            } else {
                result.put("success", false);
                result.put("message", "考试完成失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取学生考试状态
     */
    @GetMapping("/{examId}/status")
    public ResponseEntity<Map<String, Object>> getStudentExamStatus(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer studentId = (Integer) session.getAttribute("userId");
            if (studentId == null || userService.getUserById(studentId).getRole() != 2) {
                result.put("success", false);
                result.put("message", "只有学生可以查看考试状态");
                return ResponseEntity.ok(result);
            }
            
            ExamStudent examStudent = examService.getStudentExamStatus(examId, studentId);
            result.put("success", true);
            result.put("examStudent", examStudent);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 创建新题目
     */
    @PostMapping("/question/create")
    public ResponseEntity<Map<String, Object>> createQuestion(@RequestBody Question question, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null || userService.getUserById(teacherId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以创建题目");
                return ResponseEntity.ok(result);
            }
            
            if (examService.createQuestion(question)) {
                result.put("success", true);
                result.put("message", "题目创建成功");
            } else {
                result.put("success", false);
                result.put("message", "题目创建失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 更新题目
     */
    @PostMapping("/question/update")
    public ResponseEntity<Map<String, Object>> updateQuestion(@RequestBody Question question, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null || userService.getUserById(teacherId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以更新题目");
                return ResponseEntity.ok(result);
            }
            
            if (examService.updateQuestion(question)) {
                result.put("success", true);
                result.put("message", "题目更新成功");
            } else {
                result.put("success", false);
                result.put("message", "题目更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 删除题目
     */
    @PostMapping("/question/delete/{questionId}")
    public ResponseEntity<Map<String, Object>> deleteQuestion(@PathVariable Integer questionId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null || userService.getUserById(teacherId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以删除题目");
                return ResponseEntity.ok(result);
            }
            
            if (examService.deleteQuestion(questionId)) {
                result.put("success", true);
                result.put("message", "题目删除成功");
            } else {
                result.put("success", false);
                result.put("message", "题目删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取题目详情
     */
    @GetMapping("/question/{questionId}")
    public ResponseEntity<Map<String, Object>> getQuestion(@PathVariable Integer questionId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null || userService.getUserById(teacherId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看题目");
                return ResponseEntity.ok(result);
            }
            
            Question question = examService.getQuestionById(questionId);
            if (question != null) {
                result.put("success", true);
                result.put("question", question);
            } else {
                result.put("success", false);
                result.put("message", "题目不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 学生获取可参加的考试列表
     */
    @GetMapping("/available")
    public ResponseEntity<Map<String, Object>> getAvailableExams(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer studentId = (Integer) session.getAttribute("userId");
            if (studentId == null || userService.getUserById(studentId).getRole() != 2) {
                result.put("success", false);
                result.put("message", "只有学生可以参加考试");
                return ResponseEntity.ok(result);
            }
            
            List<Exam> exams = examService.getAvailableExams();
            result.put("success", true);
            result.put("exams", exams);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 学生开始考试 - 随机生成题目
     */
    @PostMapping("/start/{examId}")
    public ResponseEntity<Map<String, Object>> startExam(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer studentId = (Integer) session.getAttribute("userId");
            if (studentId == null || userService.getUserById(studentId).getRole() != 2) {
                result.put("success", false);
                result.put("message", "只有学生可以参加考试");
                return ResponseEntity.ok(result);
            }
            
            // 检查学生是否已经参加过这个考试
            if (examService.hasStudentTakenExam(examId, studentId)) {
                result.put("success", false);
                result.put("message", "您已经参加过这个考试");
                return ResponseEntity.ok(result);
            }
            
            // 从老师已添加的题目中随机选择考试题目
            List<Question> questions = examService.generateRandomQuestions(examId);
            if (questions.isEmpty()) {
                result.put("success", false);
                result.put("message", "老师还没有添加题目到考试中，或者没有足够的题目");
                return ResponseEntity.ok(result);
            }
            
            // 更新学生考试状态为进行中
            if (!examService.startExam(examId, studentId)) {
                result.put("success", false);
                result.put("message", "开始考试失败，请重试");
                return ResponseEntity.ok(result);
            }
            
            result.put("success", true);
            result.put("questions", questions);
            result.put("exam", examService.getExamById(examId));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 学生提交考试答案
     */
    @PostMapping("/submit/{examId}")
    public ResponseEntity<Map<String, Object>> submitExam(@PathVariable Integer examId, 
                                                         @RequestBody Map<String, Object> request, 
                                                         HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer studentId = (Integer) session.getAttribute("userId");
            if (studentId == null || userService.getUserById(studentId).getRole() != 2) {
                result.put("success", false);
                result.put("message", "只有学生可以提交考试");
                return ResponseEntity.ok(result);
            }
            
            @SuppressWarnings("unchecked")
            Map<String, String> answers = (Map<String, String>) request.get("answers");
            if (answers == null || answers.isEmpty()) {
                result.put("success", false);
                result.put("message", "请至少回答一道题目");
                return ResponseEntity.ok(result);
            }
            
            // 提交答案并计算成绩
            ExamRecord examRecord = examService.submitExamAnswers(examId, studentId, answers);
            
            result.put("success", true);
            result.put("message", "考试提交成功");
            result.put("score", examRecord.getScore());
            result.put("totalQuestions", examRecord.getTotalQuestions());
            result.put("percentage", examRecord.getScorePercentage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 学生查看自己的考试记录
     */
    @GetMapping("/my-records")
    public ResponseEntity<Map<String, Object>> getMyExamRecords(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer studentId = (Integer) session.getAttribute("userId");
            if (studentId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                return ResponseEntity.ok(result);
            }
            
            if (userService.getUserById(studentId).getRole() != 2) {
                result.put("success", false);
                result.put("message", "只有学生可以查看考试记录");
                return ResponseEntity.ok(result);
            }
            
            List<ExamRecord> records = examService.getStudentExamRecords(studentId);
            
            // 为每个考试记录计算基于实际回答题目的统计信息
            for (ExamRecord record : records) {
                List<ExamAnswer> answers = examService.getStudentExamAnswers(record.getExamId(), studentId);
                
                // 过滤出学生实际回答的题目（非空答案）
                List<ExamAnswer> answeredQuestions = new ArrayList<>();
                if (answers != null) {
                    for (ExamAnswer answer : answers) {
                        if (answer.getStudentAnswer() != null && !answer.getStudentAnswer().trim().isEmpty()) {
                            answeredQuestions.add(answer);
                        }
                    }
                }
                
                // 计算统计信息
                int totalAnswered = answeredQuestions.size();
                int correctCount = 0;
                for (ExamAnswer answer : answeredQuestions) {
                    if (answer.getStudentAnswer() != null && 
                        answer.getStudentAnswer().trim().equals(answer.getCorrectAnswer().trim())) {
                        correctCount++;
                    }
                }
                
                // 更新记录中的统计信息
                record.setTotalQuestions(totalAnswered);
                record.setScore(correctCount);
                
                System.out.println("=== ExamController.getMyExamRecords Debug ===");
                System.out.println("Exam ID: " + record.getExamId() + ", Student ID: " + studentId);
                System.out.println("Original total questions: " + answers.size());
                System.out.println("Answered questions: " + totalAnswered);
                System.out.println("Correct answers: " + correctCount);
                System.out.println("Updated record - Total: " + record.getTotalQuestions() + ", Score: " + record.getScore());
                System.out.println("=== End Debug ===");
            }
            
            result.put("success", true);
            result.put("records", records);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 学生查看考试详细答题记录
     */
    @GetMapping("/answer-detail/{examId}")
    public ResponseEntity<Map<String, Object>> getExamAnswerDetail(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer studentId = (Integer) session.getAttribute("userId");
            if (studentId == null || userService.getUserById(studentId).getRole() != 2) {
                result.put("success", false);
                result.put("message", "只有学生可以查看答题详情");
                return ResponseEntity.ok(result);
            }
            
            // 获取考试基本信息
            Exam exam = examService.getExamById(examId);
            if (exam == null) {
                result.put("success", false);
                result.put("message", "考试不存在");
                return ResponseEntity.ok(result);
            }
            
            List<ExamAnswer> allAnswers = examService.getStudentExamAnswers(examId, studentId);
            ExamRecord record = examService.getStudentExamRecord(examId, studentId);
            
            // 过滤出学生实际回答的题目（非空答案）
            List<ExamAnswer> answeredQuestions = new ArrayList<>();
            if (allAnswers != null) {
                for (ExamAnswer answer : allAnswers) {
                    if (answer.getStudentAnswer() != null && !answer.getStudentAnswer().trim().isEmpty()) {
                        answeredQuestions.add(answer);
                    }
                }
            }
            
            // 计算统计信息
            int totalAnswered = answeredQuestions.size();
            int correctCount = 0;
            for (ExamAnswer answer : answeredQuestions) {
                if (answer.getStudentAnswer() != null && 
                    answer.getStudentAnswer().trim().equals(answer.getCorrectAnswer().trim())) {
                    correctCount++;
                }
            }
            
            // 调试日志
            System.out.println("=== ExamController.getExamAnswerDetail Debug ===");
            System.out.println("Exam ID: " + examId + ", Student ID: " + studentId);
            System.out.println("Total questions in exam: " + (allAnswers != null ? allAnswers.size() : 0));
            System.out.println("Answered questions: " + totalAnswered);
            System.out.println("Correct answers: " + correctCount);
            System.out.println("Accuracy: " + (totalAnswered > 0 ? (correctCount * 100.0 / totalAnswered) : 0) + "%");
            
            if (answeredQuestions != null && !answeredQuestions.isEmpty()) {
                for (ExamAnswer answer : answeredQuestions) {
                    System.out.println("Answer - Question ID: " + answer.getQuestionId() + 
                        ", Student Answer: '" + answer.getStudentAnswer() + "'" +
                        ", Correct Answer: '" + answer.getCorrectAnswer() + "'" +
                        ", Question Content: '" + answer.getQuestionContent() + "'");
                }
            }
            System.out.println("=== End Debug ===");
            
            // 更新考试记录中的统计信息
            if (record != null) {
                record.setTotalQuestions(totalAnswered);
                record.setScore((int) (totalAnswered > 0 ? (correctCount * 100.0 / totalAnswered) : 0));
            }
            
            result.put("success", true);
            result.put("exam", exam);
            result.put("answers", answeredQuestions); // 只返回学生实际回答的题目
            result.put("record", record);
            result.put("statistics", Map.of(
                "totalAnswered", totalAnswered,
                "correctCount", correctCount,
                "accuracy", totalAnswered > 0 ? (correctCount * 100.0 / totalAnswered) : 0
            ));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 老师查看考试的所有学生答题记录
     */
    @GetMapping("/teacher/answers/{examId}")
    public ResponseEntity<Map<String, Object>> getExamAllAnswers(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = (Integer) session.getAttribute("userId");
            if (teacherId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(teacherId);
            if (user == null || (user.getRole() != 1 && user.getRole() != 0)) {
                result.put("success", false);
                result.put("message", "只有老师和管理员可以查看答题记录");
                return ResponseEntity.ok(result);
            }
            
            // 验证用户是否有权限查看这个考试
            Exam exam = examService.getExamById(examId);
            if (exam == null) {
                result.put("success", false);
                result.put("message", "考试不存在");
                return ResponseEntity.ok(result);
            }
            
            // 管理员可以查看任何考试，老师只能查看自己的考试
            if (user.getRole() == 1 && !exam.getTeacherId().equals(teacherId)) {
                result.put("success", false);
                result.put("message", "没有权限查看此考试的答题记录");
                return ResponseEntity.ok(result);
            }
            
            List<ExamAnswer> answers = examService.getExamAllAnswers(examId);
            List<ExamRecord> records = examService.getExamRecords(examId);
            
            // 根据学生实际答题情况重新计算每个学生的分数和统计信息
            if (records != null && !records.isEmpty()) {
                for (ExamRecord record : records) {
                    // 获取该学生的所有答题记录
                    List<ExamAnswer> studentAnswers = examService.getStudentExamAnswers(examId, record.getStudentId());
                    
                    // 过滤出学生实际回答的题目（非空答案）
                    List<ExamAnswer> answeredQuestions = new ArrayList<>();
                    if (studentAnswers != null) {
                        for (ExamAnswer answer : studentAnswers) {
                            if (answer.getStudentAnswer() != null && !answer.getStudentAnswer().trim().isEmpty()) {
                                answeredQuestions.add(answer);
                            }
                        }
                    }
                    
                    // 计算统计信息
                    int totalAnswered = answeredQuestions.size();
                    int correctCount = 0;
                    for (ExamAnswer answer : answeredQuestions) {
                        if (answer.getStudentAnswer() != null && 
                            answer.getStudentAnswer().trim().equals(answer.getCorrectAnswer().trim())) {
                            correctCount++;
                        }
                    }
                    
                    // 更新记录中的统计信息
                    record.setTotalQuestions(totalAnswered);
                    record.setScore(correctCount);
                    
                    System.out.println("=== ExamController.getExamAllAnswers Debug ===");
                    System.out.println("Student ID: " + record.getStudentId() + ", Student Name: " + record.getStudentName());
                    System.out.println("Total questions answered: " + totalAnswered);
                    System.out.println("Correct answers: " + correctCount);
                    System.out.println("Updated record - Total: " + record.getTotalQuestions() + ", Score: " + record.getScore());
                    System.out.println("=== End Debug ===");
                }
            }
            
            // 调试日志
            System.out.println("=== ExamController.getExamAllAnswers Summary ===");
            System.out.println("Exam ID: " + examId);
            System.out.println("Answers count: " + (answers != null ? answers.size() : 0));
            System.out.println("Records count: " + (records != null ? records.size() : 0));
            System.out.println("=== End Summary ===");
            
            result.put("success", true);
            result.put("answers", answers);
            result.put("records", records);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }


    /**
     * 老师更新考试
     */
    @PutMapping("/update/{examId}")
    public ResponseEntity<Map<String, Object>> updateExam(@PathVariable Integer examId, 
                                                        @RequestBody Exam exam, 
                                                        HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(userId);
            if (user == null || (user.getRole() != 1 && user.getRole() != 0)) {
                result.put("success", false);
                result.put("message", "只有老师和管理员可以更新考试");
                return ResponseEntity.ok(result);
            }
            
            // 验证用户是否有权限更新这个考试
            Exam existingExam = examService.getExamById(examId);
            if (existingExam == null) {
                result.put("success", false);
                result.put("message", "考试不存在");
                return ResponseEntity.ok(result);
            }
            
            // 管理员可以更新任何考试，老师只能更新自己的考试
            if (user.getRole() == 1 && !existingExam.getTeacherId().equals(userId)) {
                result.put("success", false);
                result.put("message", "没有权限更新此考试");
                return ResponseEntity.ok(result);
            }
            
            exam.setId(examId);
            exam.setTeacherId(userId);
            
            if (examService.updateExam(exam)) {
                result.put("success", true);
                result.put("message", "考试更新成功");
            } else {
                result.put("success", false);
                result.put("message", "考试更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员获取所有考试列表
     */
    @GetMapping("/admin/all")
    public ResponseEntity<Map<String, Object>> getAllExams(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以查看所有考试");
                return ResponseEntity.ok(result);
            }
            
            List<Exam> exams = examService.getAllExams();
            result.put("success", true);
            result.put("exams", exams);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员发布考试
     */
    @PutMapping("/admin/publish/{examId}")
    public ResponseEntity<Map<String, Object>> adminPublishExam(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以发布考试");
                return ResponseEntity.ok(result);
            }
            
            if (examService.publishExam(examId)) {
                result.put("success", true);
                result.put("message", "考试发布成功");
            } else {
                result.put("success", false);
                result.put("message", "考试发布失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员取消发布考试
     */
    @PutMapping("/admin/unpublish/{examId}")
    public ResponseEntity<Map<String, Object>> adminUnpublishExam(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以取消发布考试");
                return ResponseEntity.ok(result);
            }
            
            if (examService.unpublishExam(examId)) {
                result.put("success", true);
                result.put("message", "考试取消发布成功");
            } else {
                result.put("success", false);
                result.put("message", "考试取消发布失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员停止考试
     */
    @PutMapping("/admin/stop/{examId}")
    public ResponseEntity<Map<String, Object>> adminStopExam(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以停止考试");
                return ResponseEntity.ok(result);
            }
            
            Exam exam = examService.getExamById(examId);
            if (exam == null) {
                result.put("success", false);
                result.put("message", "考试不存在");
                return ResponseEntity.ok(result);
            }
            
            if (exam.getStatus() != 1) {
                result.put("success", false);
                result.put("message", "只有已发布的考试才能停止");
                return ResponseEntity.ok(result);
            }
            
            exam.setStatus(2); // 设置为已停止状态
            if (examService.updateExam(exam)) {
                result.put("success", true);
                result.put("message", "考试已停止");
            } else {
                result.put("success", false);
                result.put("message", "停止考试失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员删除考试
     */
    @DeleteMapping("/admin/delete/{examId}")
    public ResponseEntity<Map<String, Object>> adminDeleteExam(@PathVariable Integer examId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以删除考试");
                return ResponseEntity.ok(result);
            }
            
            if (examService.deleteExam(examId)) {
                result.put("success", true);
                result.put("message", "考试删除成功");
            } else {
                result.put("success", false);
                result.put("message", "考试删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 更新考试应考题目数量
     */
    @PutMapping("/{examId}/update-exam-questions")
    public ResponseEntity<Map<String, Object>> updateExamQuestions(@PathVariable Integer examId, 
                                                                  @RequestBody Map<String, Object> requestData, 
                                                                  HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }
            
            User user = userService.getUserById(userId);
            if (user == null || (user.getRole() != 1 && user.getRole() != 0)) {
                result.put("success", false);
                result.put("message", "只有老师和管理员可以更新考试配置");
                return ResponseEntity.ok(result);
            }
            
            Integer examQuestions = (Integer) requestData.get("examQuestions");
            if (examQuestions == null || examQuestions < 1) {
                result.put("success", false);
                result.put("message", "应考题目数量必须大于0");
                return ResponseEntity.ok(result);
            }
            
            if (examService.updateExamQuestions(examId, examQuestions)) {
                result.put("success", true);
                result.put("message", "考试配置更新成功");
            } else {
                result.put("success", false);
                result.put("message", "更新考试配置失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    // 自动保存答案
    @PostMapping("/auto-save/{examId}")
    public ResponseEntity<Map<String, Object>> autoSaveAnswers(
            @PathVariable Integer examId,
            @RequestBody Map<String, String> answers,
            HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }

            System.out.println("=== 自动保存答案调试 ===");
            System.out.println("考试ID: " + examId);
            System.out.println("学生ID: " + currentUser.getId());
            System.out.println("接收到的答案: " + answers);
            System.out.println("答案数量: " + answers.size());
            
            // 调用服务层保存答案
            boolean saveResult = examService.autoSaveExamAnswers(examId, currentUser.getId(), answers);
            
            if (saveResult) {
                result.put("success", true);
                result.put("message", "答案自动保存成功");
                System.out.println("自动保存成功");
            } else {
                result.put("success", false);
                result.put("message", "答案自动保存失败");
                System.out.println("自动保存失败");
            }
            
            System.out.println("=== 自动保存结束 ===");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
            System.out.println("自动保存异常: " + e.getMessage());
            e.printStackTrace();
        }
        return ResponseEntity.ok(result);
    }
}